#version 150
uniform sampler2D sampler0;
uniform vec2 samplerSize0;

in vec3 normal;
in vec4 color;
in vec4 texcoord0;

out vec4 frag_color;

//
// This filter converts the texture color to grayscale, brightens it, and creates an inset bevel from the alpha values.
// The bevel is inside the shape, and texels with coordinates outside the range [0, 1> are treated as zero.
// This ensures the bevel will be properly rendered, even if the border pixels have nonzero alpha, as long as 
// -The entire texture is rendered, e.g. input coordinates are 0,0 in the upper left and 1,1 in the lower right,
// -No filtering is used, e.g. GL_NEAREST filtering mode is used across both dimensions, and
// -The texture is not scaled, e.g. each texel maps to one and only one screen pixel.
//
void main() {
	//Base color to compute grayscale
    vec4 tmp = color * texture2DProj(sampler0, texcoord0);
    //Texel units in x and y direction
    float unx = 1.0/samplerSize0.x;
    float uny = 1.0/samplerSize0.y;
    //Find four neighbour texel alpha in order to create bevel effect
    //If coordinates are out of range, clamp alpha to zero
    vec2 nCoord = texcoord0.xy + vec2( 0.0,-uny);
    float na = (color * texture2D(sampler0, nCoord)).a * float( nCoord.y >= 0.0 );
    vec2 wCoord = texcoord0.xy + vec2(-unx, 0.0);
    float wa = (color * texture2D(sampler0, wCoord)).a * float( wCoord.x >= 0.0 );
    vec2 eCoord = texcoord0.xy + vec2( unx, 0.0);
    float ea = (color * texture2D(sampler0, eCoord)).a * float( eCoord.x < 1.0 );
    vec2 sCoord = texcoord0.xy + vec2( 0.0, uny);
    float sa = (color * texture2D(sampler0, sCoord)).a * float( sCoord.y < 1.0 );
    
    //Use YUV weights to compute grayscale
    float gray = dot(tmp, vec4(0.30, 0.59, 0.11, 0.00));
    //Bevel and clamp to normalized range
    gray = clamp(gray + na + wa - ea - sa, 0.0, 1.0);
    //Brighten, affecting dark values the most
    gray = (1 + gray)/2.0;
    //Emit grayscale color and original alpha(bevel is inside shape)
    frag_color = vec4(gray, gray, gray, tmp.a);
}